package waiter.core.config;

import waiter.core.config.properties.DruidProperties;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@MapperScan(basePackages={"**.mapper"})
@ConditionalOnProperty(prefix="spring.datasource", name={"url"})
public class MybatisDataSourceAutoConfiguration
{

  @Autowired
  private DruidProperties druidProperties;

  @Bean
  @ConfigurationProperties(prefix="spring.datasource")
  public DruidProperties druidProperties()
  {
    return new DruidProperties();
  }

  @Bean
  public PaginationInterceptor paginationInterceptor()
  {
    PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
    paginationInterceptor.setDialectType(DBType.MYSQL.getDb());
    return paginationInterceptor;
  }

  @Bean(initMethod="init")
  public DruidDataSource dataSource()
  {
    DruidDataSource dataSource = new DruidDataSource();
    this.druidProperties.config(dataSource);
    return dataSource;
  }
}